package ar.republicagroup.gestion.view;

import ar.republicagroup.gestion.entities.Cheque;
import ar.republicagroup.gestion.entities.Cliente;
import ar.republicagroup.gestion.entities.ClienteSaldo;
import ar.republicagroup.gestion.entities.Liquidacion;
import ar.republicagroup.gestion.entities.LiquidacionDetalle;
import ar.republicagroup.gestion.services.ClienteSaldoServices;
import ar.republicagroup.gestion.services.ClienteServices;
import ar.republicagroup.gestion.services.ExportarServices;
import ar.republicagroup.gestion.services.LiquidacionServices;
import ar.republicagroup.gestion.util.JComboBoxModel;
import ar.republicagroup.gestion.util.SpringUtils;
import ar.republicagroup.gestion.util.TableColumnAdjuster;
import ar.republicagroup.gestion.util.exportar.ReportModel;
import ar.republicagroup.gestion.util.helpers.Formato;
import ar.republicagroup.gestion.util.messages.UIMessages;
import java.awt.HeadlessException;
import java.awt.Toolkit;
import java.awt.print.PrinterException;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.SwingWorker;
import javax.swing.table.DefaultTableModel;
import org.apache.log4j.Logger;

/**
 *
 * @author DIEGOALV
 */
public class frmReporteLiquidacion extends javax.swing.JDialog {
    /* Services */
    ExportarServices exportarServices               = (ExportarServices)SpringUtils.getBean("exportarServices");
    LiquidacionServices liquidacionServices         = (LiquidacionServices)SpringUtils.getBean("liquidacionServices");
    ClienteServices clienteServices                 = (ClienteServices)SpringUtils.getBean("clienteServices");
    ClienteSaldoServices clienteSaldoServices       = (ClienteSaldoServices)SpringUtils.getBean("clienteSaldoServices");
    /* List */
    List<Liquidacion> liquidacionList = new ArrayList();
    
    /* Logging */
    static Logger log = Logger.getLogger(frmReporteLiquidacion.class);
    
    private Task task;
    
    public frmReporteLiquidacion(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        valoresPorDefecto();
        cargarDatos();
    }

   
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jPanel2 = new javax.swing.JPanel();
        dateChooserDesde = new com.toedter.calendar.JDateChooser();
        dateChooserHasta = new com.toedter.calendar.JDateChooser();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        comboClientes = new javax.swing.JComboBox();
        btnBuscar = new javax.swing.JButton();
        jPanel3 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tblLiquidacion = new javax.swing.JTable();
        jPanel4 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        tblDetalleLiquid = new javax.swing.JTable();
        jPanel5 = new javax.swing.JPanel();
        jLabel8 = new javax.swing.JLabel();
        lblTotalCap = new javax.swing.JLabel();
        jLabel9 = new javax.swing.JLabel();
        lblVC = new javax.swing.JLabel();
        jLabel10 = new javax.swing.JLabel();
        lblGastos = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        lblTotalLiquidacion = new javax.swing.JLabel();
        jLabel14 = new javax.swing.JLabel();
        lblPagado = new javax.swing.JLabel();
        jLabel12 = new javax.swing.JLabel();
        lblRechazos = new javax.swing.JLabel();
        jPanel6 = new javax.swing.JPanel();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        jLabel11 = new javax.swing.JLabel();
        lblChequesTotales = new javax.swing.JLabel();
        lblChequesLiquidados = new javax.swing.JLabel();
        lblChequesPendientes = new javax.swing.JLabel();
        lblChequesRechazados = new javax.swing.JLabel();
        jPanel7 = new javax.swing.JPanel();
        btnExportar = new javax.swing.JButton();
        btnPago = new javax.swing.JButton();
        btnImprimir = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("..: Reporte de liquidaciones :...");

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Ver"));

        jLabel1.setText("Desde");

        jLabel2.setText("Hasta");

        jLabel3.setText("Cliente");

        btnBuscar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ar/republicagroup/gestion/view/images/search_2.png"))); // NOI18N
        btnBuscar.setText("Buscar");
        btnBuscar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnBuscarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGap(29, 29, 29)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel3)
                    .addComponent(jLabel1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(dateChooserDesde, javax.swing.GroupLayout.PREFERRED_SIZE, 129, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(dateChooserHasta, javax.swing.GroupLayout.PREFERRED_SIZE, 128, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(btnBuscar))
                    .addComponent(comboClientes, javax.swing.GroupLayout.PREFERRED_SIZE, 177, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(btnBuscar)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel3)
                            .addComponent(comboClientes, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(dateChooserHasta, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel1)
                            .addComponent(dateChooserDesde, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel2))))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("Liquidaciones"));

        tblLiquidacion.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "#", "Fecha", "Hora", "Cliente", "Liquidación", "Dif.Liq.Ant", "Total", "Pagado", "Usuario"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, false, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tblLiquidacion.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
        tblLiquidacion.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        tblLiquidacion.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tblLiquidacionMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(tblLiquidacion);

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 465, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addGap(23, 23, 23)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 286, Short.MAX_VALUE)
                .addContainerGap())
        );

        jPanel4.setBorder(javax.swing.BorderFactory.createTitledBorder("Detalle de liquidación"));

        tblDetalleLiquid.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Nro", "Banco", "Origen", "Importe", "Comisión", "Estado"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tblDetalleLiquid.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
        jScrollPane2.setViewportView(tblDetalleLiquid);

        jPanel5.setBorder(javax.swing.BorderFactory.createTitledBorder("Totales"));

        jLabel8.setText("CAP");

        lblTotalCap.setText("0");

        jLabel9.setText("VC");

        lblVC.setText("0");

        jLabel10.setText("Gastos");

        lblGastos.setText("0");

        jLabel4.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel4.setText("Total");

        lblTotalLiquidacion.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        lblTotalLiquidacion.setText("0");

        jLabel14.setText("Pagado");

        lblPagado.setText("0");

        jLabel12.setText("Rechazos");

        lblRechazos.setText("0");

        javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5);
        jPanel5.setLayout(jPanel5Layout);
        jPanel5Layout.setHorizontalGroup(
            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel5Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel5Layout.createSequentialGroup()
                        .addComponent(jLabel8)
                        .addGap(18, 18, 18)
                        .addComponent(lblTotalCap)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jLabel9))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel5Layout.createSequentialGroup()
                        .addComponent(jLabel10)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(lblGastos)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 112, Short.MAX_VALUE)
                        .addComponent(jLabel12))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel5Layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel14, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel4, javax.swing.GroupLayout.Alignment.TRAILING))))
                .addGap(18, 18, 18)
                .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lblVC)
                    .addComponent(lblRechazos)
                    .addComponent(lblTotalLiquidacion)
                    .addComponent(lblPagado))
                .addGap(50, 50, 50))
        );
        jPanel5Layout.setVerticalGroup(
            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel5Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel8)
                    .addComponent(lblTotalCap)
                    .addComponent(jLabel9)
                    .addComponent(lblVC))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel10)
                    .addComponent(lblGastos)
                    .addComponent(jLabel12)
                    .addComponent(lblRechazos))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(lblTotalLiquidacion))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblPagado)
                    .addComponent(jLabel14))
                .addContainerGap(22, Short.MAX_VALUE))
        );

        jPanel6.setBorder(javax.swing.BorderFactory.createTitledBorder("Cheques"));

        jLabel5.setText("Total");

        jLabel6.setText("Liquidados");

        jLabel7.setText("Rechazados");

        jLabel11.setText("Pendientes ");

        lblChequesTotales.setText("0");

        lblChequesLiquidados.setText("0");

        lblChequesPendientes.setText("0");

        lblChequesRechazados.setText("0");

        javax.swing.GroupLayout jPanel6Layout = new javax.swing.GroupLayout(jPanel6);
        jPanel6.setLayout(jPanel6Layout);
        jPanel6Layout.setHorizontalGroup(
            jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel6Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel6Layout.createSequentialGroup()
                        .addComponent(jLabel11)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(lblChequesPendientes))
                    .addGroup(jPanel6Layout.createSequentialGroup()
                        .addComponent(jLabel5)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(lblChequesTotales))
                    .addGroup(jPanel6Layout.createSequentialGroup()
                        .addComponent(jLabel7)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 84, Short.MAX_VALUE)
                        .addComponent(lblChequesRechazados))
                    .addGroup(jPanel6Layout.createSequentialGroup()
                        .addComponent(jLabel6)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(lblChequesLiquidados)))
                .addContainerGap())
        );
        jPanel6Layout.setVerticalGroup(
            jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel6Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel6)
                    .addComponent(lblChequesLiquidados))
                .addGap(11, 11, 11)
                .addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel11)
                    .addComponent(lblChequesPendientes))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel7)
                    .addComponent(lblChequesRechazados))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblChequesTotales)
                    .addComponent(jLabel5))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel4Layout.createSequentialGroup()
                        .addGap(14, 14, 14)
                        .addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 50, Short.MAX_VALUE)
                        .addComponent(jPanel6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel4Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jScrollPane2)))
                .addContainerGap())
        );
        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel4Layout.createSequentialGroup()
                .addGap(26, 26, 26)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 240, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel6, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );

        jPanel7.setBorder(javax.swing.BorderFactory.createTitledBorder("Seleccione liquidación"));

        btnExportar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ar/republicagroup/gestion/view/images/pdf.png"))); // NOI18N
        btnExportar.setText("Exportar");
        btnExportar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnExportarActionPerformed(evt);
            }
        });

        btnPago.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ar/republicagroup/gestion/view/images/32_money_bag.png"))); // NOI18N
        btnPago.setText("Pago");
        btnPago.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnPagoActionPerformed(evt);
            }
        });

        btnImprimir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ar/republicagroup/gestion/view/images/printer_32.png"))); // NOI18N
        btnImprimir.setText("Imprimir");
        btnImprimir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnImprimirActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel7Layout = new javax.swing.GroupLayout(jPanel7);
        jPanel7.setLayout(jPanel7Layout);
        jPanel7Layout.setHorizontalGroup(
            jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel7Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(btnExportar)
                .addGap(34, 34, 34)
                .addComponent(btnPago)
                .addGap(33, 33, 33)
                .addComponent(btnImprimir)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel7Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {btnExportar, btnPago});

        jPanel7Layout.setVerticalGroup(
            jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel7Layout.createSequentialGroup()
                .addGap(20, 20, 20)
                .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnExportar)
                    .addComponent(btnPago)
                    .addComponent(btnImprimir))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap(585, Short.MAX_VALUE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jPanel7, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addGap(18, 18, 18)
                        .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 0, Short.MAX_VALUE))))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(22, 22, 22)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jPanel7, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(31, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void tblLiquidacionMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tblLiquidacionMouseClicked
        liquidacionServices.reiniciarTotales();
        int fila = tblLiquidacion.getSelectedRow();
        Liquidacion liquidacion =(Liquidacion)tblLiquidacion.getValueAt(fila, 0);
        List<LiquidacionDetalle> detalleLiquidList = liquidacion.getLiquidacionDetalleList();
        cargarTablaDetalle(detalleLiquidList);
        
        lblTotalCap.setText(""+Formato.decimalComaMilesConSigno(liquidacionServices.getTotalValoresAlCobroCAP() + liquidacionServices.getTotalRechazosCAP()));
        lblVC.setText(""+Formato.decimalComaMilesConSigno(liquidacionServices.getTotalValoresAlCobroVC() + liquidacionServices.getTotalRechazosVC())); 
        lblGastos.setText(""+Formato.decimalComaMilesConSigno(liquidacionServices.getTotalRechazados()));
        lblTotalLiquidacion.setText(""+Formato.decimalComaMilesConSigno(liquidacionServices.getTotalLiquidacion()));
        lblPagado.setText(""+Formato.decimalComaMilesConSigno(liquidacion.getImportePagado()));
        lblRechazos.setText(""+Formato.decimalComaMilesConSigno(liquidacionServices.getTotalRechazos()));
        lblChequesLiquidados.setText(""+liquidacionServices.getNroDeChequesLiquidados());
        lblChequesPendientes.setText(""+liquidacionServices.getNroDeChequesPendientes());
        lblChequesRechazados.setText(""+liquidacionServices.getNroDeChequesRechazados());
        lblChequesTotales.setText(""+liquidacionServices.getNroTotalDeCheques());
        btnExportar.setEnabled(true);
        
    }//GEN-LAST:event_tblLiquidacionMouseClicked

    private void btnBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBuscarActionPerformed
       buscarLiquidaciones();      
    }//GEN-LAST:event_btnBuscarActionPerformed

    private void btnExportarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnExportarActionPerformed
        
        int fila = tblLiquidacion.getSelectedRow();
        if(fila > -1){
            
        final BarraDeProgreso barra;
        barra = new BarraDeProgreso(this, false);
        barra.setLocationRelativeTo(this);
        barra.setVisible(true);
        
            task = new Task();
            task.addPropertyChangeListener(new PropertyChangeListener() {

             @Override
             public void propertyChange(PropertyChangeEvent pcEvt) {
                if (SwingWorker.StateValue.DONE == pcEvt.getNewValue()) {
                   Toolkit.getDefaultToolkit().beep(); 
                   barra.setVisible(false);
                   barra.dispose();            
                }
             }
          });
       
        task.execute(); 
                  
        } else {
            JOptionPane.showMessageDialog(this, UIMessages.getErrorMessage("requiredSelectedLiquidacion"), UIMessages.getErrorMessage("defaultErrorTitle"), JOptionPane.ERROR_MESSAGE);
            btnExportar.setEnabled(false);
        }   
    }//GEN-LAST:event_btnExportarActionPerformed

    private void btnPagoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnPagoActionPerformed
        int fila = tblLiquidacion.getSelectedRow();
        if(fila > -1){
            Liquidacion liquidacion         = (Liquidacion)tblLiquidacion.getValueAt(fila, 0);
            if(liquidacion.getImportePagado() == 0 && liquidacion.getPosponer_pago().equals("N")){
                ClienteSaldo saldoCliente       = clienteSaldoServices.getSaldoActualByCliente(liquidacion.getClienteId());
                modalPanelAddPago panelPago     = new modalPanelAddPago(null, true);
                panelPago.setLocationRelativeTo(this);
                panelPago.setLiquidacion(liquidacion);
                panelPago.setClienteSaldo(saldoCliente);
                panelPago.setVisible(true);    
            } else {
                JOptionPane.showMessageDialog(this, UIMessages.getInfoMessage("payment_disabled"), UIMessages.getInfoMessage("defaultInfoTitle"), JOptionPane.INFORMATION_MESSAGE);
            }
        }else{
            JOptionPane.showMessageDialog(this, UIMessages.getErrorMessage("requiredSelectedLiquidacion"), UIMessages.getErrorMessage("defaultErrorTitle"), JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_btnPagoActionPerformed

    private void btnImprimirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnImprimirActionPerformed
         int fila = tblLiquidacion.getSelectedRow();
         if(fila > -1){
            imprimirReporteDeLiquidacion();
         }else{
            JOptionPane.showMessageDialog(this, UIMessages.getErrorMessage("requiredSelectedLiquidacion"), UIMessages.getErrorMessage("defaultErrorTitle"), JOptionPane.ERROR_MESSAGE);
         }
    }//GEN-LAST:event_btnImprimirActionPerformed

    
    private void imprimirReporteDeLiquidacion(){
    
    try {
            MessageFormat header = new MessageFormat(UIMessages.getInfoMessage("detalleLiquidacion_title"),new Locale("es","ES"));
            MessageFormat footer = new MessageFormat(UIMessages.getInfoMessage("detalleLiquidacion_footer") + liquidacionServices.getTotalLiquidacion());
            boolean imprimio = tblDetalleLiquid.print(JTable.PrintMode.FIT_WIDTH, header, footer, true, null, true);
            if(imprimio){
                log.info("Imprimió reporte de Totales por cuenta...");
            }
        } catch (PrinterException ex) {
            log.error("Error al imprimir...");
            log.error(ex.getMessage(),ex);
        } catch (HeadlessException ex) {
            log.error(ex.getMessage(),ex);
            log.error("Sin encabezado ...");
        }
    
    }
 
    
    class Task extends SwingWorker<Void, Void> {
        /*
         * Main task. Executed in background thread.
         */
        @Override
        public Void doInBackground() throws Exception {
             exportarReportePDF();
             return null;
        }
    }
    
    public void exportarReportePDF(){
        
        
        
        int fila = tblLiquidacion.getSelectedRow();
        Liquidacion liquidacion =(Liquidacion)tblLiquidacion.getValueAt(fila, 0);
        List<LiquidacionDetalle> detalleLiquidList = liquidacion.getLiquidacionDetalleList();
        liquidacionServices.setCliente(liquidacion.getClienteId());
        
        log.info("Exportando la liquidacion ---> "+liquidacion.getId());
        
        ClienteSaldo saldoCliente = clienteSaldoServices.getSaldoActualByCliente(liquidacion.getClienteId());
        /* Parametros para enviar al reporte PDF*/
         Map parametros = new HashMap();
         parametros.put("fecha", Formato.cambiarFechaAFormatoLocal(liquidacion.getFechaRegistro()));
         parametros.put("cliente",liquidacion.getClienteId().getNombre());
         parametros.put("valores_al_cobro_prov",Formato.decimalComaMiles(liquidacionServices.getTotalValoresAlCobroVC() + liquidacionServices.getTotalRechazosVC()));
         parametros.put("valores_al_cobro_cap",Formato.decimalComaMiles(liquidacionServices.getTotalValoresAlCobroCAP()+ liquidacionServices.getTotalRechazosCAP()));
         parametros.put("com_gestion",Formato.decimalComaMilesConSigno(liquidacionServices.getTotalComGestion()));
         parametros.put("com_cap",liquidacionServices.getComisionCAP());
         parametros.put("com_vc",liquidacionServices.getComisionVC());
         
         if(liquidacion.getTotalLiquidacion() < liquidacion.getSaldoCliente()){
                parametros.put("saldo",Formato.decimalComaMiles(liquidacion.getTotalLiquidacion() + (liquidacion.getSaldoCliente())));
         }else {
                parametros.put("saldo",Formato.decimalComaMiles(liquidacion.getTotalLiquidacion() + (liquidacion.getSaldoCliente()*(-1))));
         }
         
         parametros.put("subtotal_cap",Formato.decimalComaMiles(liquidacionServices.getSubtotalCAP()));
         parametros.put("subtotal_vc",Formato.decimalComaMiles(liquidacionServices.getSubtotalVC()));
         parametros.put("subtotal_gestion",Formato.decimalComaMiles(liquidacionServices.getSubtotalGestion()));
         parametros.put("total_rechazado",liquidacionServices.getTotalRechazados());
         parametros.put("total_pagado", Formato.decimalComaMiles(liquidacion.getImportePagado()));
         parametros.put("total_gestion", Formato.decimalComaMiles(liquidacionServices.getTotalLiquidacion()));
         parametros.put("liquid_anterior", Formato.decimalComaMilesConSigno(liquidacion.getSaldoCliente()));
         parametros.put("notas",liquidacion.getNota());
         
         List<Cheque> chequeList = new ArrayList<>();
         for(LiquidacionDetalle detalleLiquid : detalleLiquidList){
                chequeList.add(detalleLiquid.getChequeId());
            }
         
         
        try {
                exportarServices.reporteDeLiquidacionesToPDF(ReportModel.reporteDeLiquidacion(chequeList), parametros);
            } catch (Exception ex) {
                log.error("Error exportando PDF en Reporte de Liquidacion",ex);
                JOptionPane.showMessageDialog(this, UIMessages.getErrorMessage("onExportError"), UIMessages.getErrorMessage("defaultErrorTitle"),JOptionPane.ERROR_MESSAGE);
            }
    
    }
    
    
    
    
    private void buscarLiquidaciones(){
        Date fechaDesde         = dateChooserDesde.getDate();
        Date fechaHasta         = dateChooserHasta.getDate();
        JComboBoxModel model    =(JComboBoxModel)comboClientes.getSelectedItem();
        Cliente cliente         = clienteServices.get(Integer.parseInt(model.getValue()));
        liquidacionList         = liquidacionServices.getLiquidacionsByFilters(cliente, fechaDesde, fechaHasta);
        cargarTabla(liquidacionList);
    }
    
    
    private void valoresPorDefecto(){
        dateChooserDesde.setLocale(Formato.localeDeCalendario());
        dateChooserHasta.setLocale(Formato.localeDeCalendario());
        dateChooserDesde.setDate(new Date());
        dateChooserHasta.setDate(new Date());       
    }
    
    
    private void cargarDatos(){
        liquidacionList = liquidacionServices.getLiquidacionsByFilters(null,new Date(),new Date());
        cargarTabla(liquidacionList);
        comboClientes.setModel(clienteServices.combo());
    }
    
    public void cargarTabla(List<Liquidacion> liquidacionList){
        
        try{
                DefaultTableModel model = (DefaultTableModel) tblLiquidacion.getModel();
                model.fireTableDataChanged();
                model.getDataVector().clear();
                for(Liquidacion liquidacion : liquidacionList){
                    double totalLiquidacion;
                    if(liquidacion.getTotalLiquidacion() > 0){
                        totalLiquidacion = liquidacion.getTotalLiquidacion() + (liquidacion.getSaldoCliente()*(-1));
                    }else{
                        totalLiquidacion = liquidacion.getTotalLiquidacion() + (liquidacion.getSaldoCliente());
                    }
                    
                    model.addRow(new Object[]{liquidacion,Formato.fechaDDMMYY(liquidacion.getFechaLiquidacion()),
                                              Formato.obtenerFechaYHoraDeDate(liquidacion.getFechaRegistro()),
                                              liquidacion.getClienteId().getNombre(),
                                              Formato.decimalComaMilesConSigno(liquidacion.getTotalLiquidacion()),
                                              Formato.decimalComaMilesConSigno(liquidacion.getSaldoCliente()),
                                              Formato.decimalComaMiles(totalLiquidacion),
                                              Formato.decimalComaMilesConSigno(liquidacion.getImportePagado()),
                                              liquidacion.getUsuarioId().getNombre()});
                }
        
                tblLiquidacion.setModel(model);
                TableColumnAdjuster tca = new TableColumnAdjuster(tblLiquidacion);
                tca.setColumnDataIncluded(true);
                tca.adjustColumns();
                tblLiquidacion.repaint();
            }catch(Exception ex){
                log.error(ex.getMessage(),ex);
            }
            
    }
    
    
    public void cargarTablaDetalle(List<LiquidacionDetalle> detalleLiquidList){
          try{
            DefaultTableModel model = (DefaultTableModel) tblDetalleLiquid.getModel();
            model.fireTableDataChanged();
            model.getDataVector().clear();
            
            for(LiquidacionDetalle detalleLiquid : detalleLiquidList){
                model.addRow(new Object[]{detalleLiquid.getChequeId(),detalleLiquid.getChequeId().getBancoId().getNombre(),detalleLiquid.getChequeId().getOrigen(),Formato.decimalComaMilesConSigno(detalleLiquid.getChequeId().getImporte().doubleValue()),detalleLiquid.getChequeId().getComision().doubleValue(),detalleLiquid.getChequeEstadoId().getNombre() });
                liquidacionServices.addChequeToLiquidacion(detalleLiquid.getChequeId());
            }
        
            TableColumnAdjuster tca = new TableColumnAdjuster(tblDetalleLiquid);
            tca.adjustColumns();
            tblDetalleLiquid.setModel(model);
            tblDetalleLiquid.repaint();
        }catch(Exception ex){
           log.error(ex.getMessage(),ex);
        }  
    }

    public static void main(String args[]) {
       java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                frmReporteLiquidacion dialog = new frmReporteLiquidacion(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    protected static javax.swing.JButton btnBuscar;
    private javax.swing.JButton btnExportar;
    private javax.swing.JButton btnImprimir;
    private javax.swing.JButton btnPago;
    private javax.swing.JComboBox comboClientes;
    private com.toedter.calendar.JDateChooser dateChooserDesde;
    private com.toedter.calendar.JDateChooser dateChooserHasta;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel12;
    private javax.swing.JLabel jLabel14;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JPanel jPanel6;
    private javax.swing.JPanel jPanel7;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JLabel lblChequesLiquidados;
    private javax.swing.JLabel lblChequesPendientes;
    private javax.swing.JLabel lblChequesRechazados;
    private javax.swing.JLabel lblChequesTotales;
    private javax.swing.JLabel lblGastos;
    private javax.swing.JLabel lblPagado;
    private javax.swing.JLabel lblRechazos;
    private javax.swing.JLabel lblTotalCap;
    private javax.swing.JLabel lblTotalLiquidacion;
    private javax.swing.JLabel lblVC;
    private javax.swing.JTable tblDetalleLiquid;
    private javax.swing.JTable tblLiquidacion;
    // End of variables declaration//GEN-END:variables
}
